<template>

  <div>
    <div style="margin:0 auto">
      <el-row>
        <el-col :span="6">
          <el-input
            v-model="searchInput"
            placeholder="根据员工ID查找内容"
            prefix-icon="el-icon-search"
            @input="watchsearch"
          ></el-input>
        </el-col>
        <el-col :span="4">
          <el-button @click="getEmployeeById">
            搜索
          </el-button>
        </el-col>
        <el-col :span="6">

          <el-select v-model="rolevalue" placeholder="请选择查看类型" @change="getEmployeeByRole(rolevalue)">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button @click="openInsertdialog">新建员工信息</el-button>
        </el-col>
        <el-col :span="2">

          <el-button @click="exportExcel">导出员工表</el-button>
        </el-col>
        <el-col :span="2">
            <el-button @click="returnlogin">返回首页</el-button>
        </el-col>
      </el-row>
    </div>
    <div id="tables">
      <el-table
        :data="employee"
        :row-style="{height: '0'}"
        :cell-style="{padding: '0'}"
        style="width: 100%"
        @row-click="getDetails"
        id="out-table"

      >
<!--        <el-table-column label width="35">-->
<!--          <template slot-scope="scope">-->
<!--            <el-radio :label="scope.row.name" v-model="radioId">&nbsp;</el-radio>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column align="center" prop="userId" label="员工Id" width="100" fixed></el-table-column>
        <el-table-column align="center" prop="userName" label="姓名" width="75"></el-table-column>
        <el-table-column align="center" prop="idcard" label="身份证号" width="150"></el-table-column>
        <el-table-column align="center" prop="email" label="邮箱" width="150"></el-table-column>
        <el-table-column align="center" prop="gender" label="性别" width="100"></el-table-column>
        <el-table-column align="center" prop="role" label="权限级别" width="75"></el-table-column>
        <el-table-column align="center" prop="politicaltype" label="政治面貌" width="60"></el-table-column>
        <el-table-column align="center" prop="nationId" label="民族" width="100"></el-table-column>
        <el-table-column align="center" prop="address" label="地址" width="75"></el-table-column>
        <el-table-column align="center" prop="phone" label="电话" width="60"></el-table-column>
        <el-table-column align="center" prop="education" label="最高学历" width="100"></el-table-column>
        <el-table-column align="center" prop="educationsubject" label="专业" width="75"></el-table-column>
        <el-table-column align="center" prop="school" label="毕业院校" width="60"></el-table-column>
        <el-table-column align="center" prop="departmentId" label="部门Id" width="75"></el-table-column>
        <el-table-column align="center" prop="departmentName" label="部门茗" width="60"></el-table-column>
        <el-table-column align="center" prop="workId" label="岗位Id" width="100"></el-table-column>
        <el-table-column align="center" prop="workName" label="职位" width="75"></el-table-column>
        <el-table-column align="center" prop="baseSalary" label="基本工资" width="60"></el-table-column>
        <el-table-column fixed="right" width="200" label="操作">
          <template slot-scope="scope">
            <el-button @click="opendialog(scope.row)" style="padding: 3px" size="mini">编辑</el-button>
<!--            <el-button style="padding: 3px" size="mini" type="primary">查看高级资料</el-button>-->
            <el-button @click="deleteEmp(scope.row)" style="padding: 3px" size="mini" type="danger" v-show="scope.row.role!='admin'">离职
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
      title="编辑信息"
      :visible.sync="dialogVisible"
      width="80%"
      :before-close="handleClose">

      <el-form ref="form" label-width="100px" v-model="employees" :rules="rule">

        <el-row>
          <el-col :span="6">
            <el-form-item label="员工id">
              <el-input v-model="employees.userId" disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <!--        <el-col :span="8">-->
          <!--          <el-form-item label="活动区域">-->
          <!--            <el-select v-model="employee.userId" placeholder="请选择活动区域">-->
          <!--              <el-option label="区域一" value="shanghai"></el-option>-->
          <!--              <el-option label="区域二" value="beijing"></el-option>-->
          <!--            </el-select>-->
          <!--          </el-form-item>-->
          <!--        </el-col>-->
          <el-col :span="6">
            <el-form-item label="员工姓名" >
              <el-input v-model="employees.userName" maxlength="10"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="员工性别" prop="gender">
              <el-input v-model="employees.gender" maxlength="1"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="民族" prop="nationId">
              <el-input v-model="employees.nationId" maxlength="4" ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="政治面貌" prop="politicaltype">
              <el-input v-model="employees.politicaltype" maxlength="5" ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="16">
            <el-form-item label="地址" prop="address">
              <el-input v-model="employees.address"   maxlength="25" ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="身份证号" prop="idCard">
              <el-input v-model="employees.idcard"  maxlength="18"  ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电话号码：" prop="phone">
              <el-input v-model="employees.phone"  maxlength="11" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="最高学历" prop="education">
              <el-input v-model="employees.education" maxlength="16" ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="10">
            <el-form-item label="专业" prop="educationsubject">
              <el-input v-model="employees.educationsubject" maxlength="16">

              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="毕业院校" prop="school">
              <el-input v-model="employees.school" maxlength="16" ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="部门id">
              <el-input v-model="employees.departmentId" disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门名称">
              <el-input v-model="employees.departmentName" disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="个人工号">
              <el-input v-model="employees.workId" disabled="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="职位">
              <el-input v-model="employees.workName" disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="基本工资">
              <el-input v-model="employees.baseSalary" disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="邮箱">
              <el-input v-model="employees.email"   prop="address" maxlength="20"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>


      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="submitMessage">确 定 修 改</el-button>
  </span>
    </el-dialog>


    <el-dialog
      title="新增员工信息"
      :visible.sync="insertdialogVisible"
      width="80%"
      :before-close="handleClose">

      <el-form ref="form" label-width="100px" v-model="employees" :rules="rule">

        <el-row>
          <el-col :span="6">
            <el-form-item label="未增员工Id" >
            <el-select v-model="usercache" placeholder="请选择员工" @change="getEmployeeuserId(usercache)">
              <el-option
                v-for="item in noEmployeeuser"
                :key="item.userId"
                :label="item.userId"
                :value="item.userId">
              </el-option>
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="员工姓名" prop="name">
              <el-input v-model="employees.userName" ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="员工性别" prop="gender">
              <el-input v-model="employees.gender" maxlength="1"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="民族" prop="nationId">
              <el-input v-model="employees.nationId" maxlength="4" ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="政治面貌" prop="politicaltype">
              <el-input v-model="employees.politicaltype" maxlength="5" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="权限" >
              <el-input v-model="roleinsert"   maxlength="8" disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地址" prop="address">
              <el-input v-model="employees.address"   maxlength="25" ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="身份证号" prop="idCard">
              <el-input v-model="employees.idcard"  maxlength="18"  ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电话号码：" prop="phone">
              <el-input v-model="employees.phone"  maxlength="11" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="最高学历" prop="education">
              <el-input v-model="employees.education" maxlength="16" ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="10">
            <el-form-item label="专业" prop="educationsubject">
              <el-input v-model="employees.educationsubject" maxlength="16">

              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="毕业院校" prop="school">
              <el-input v-model="employees.school" maxlength="16" ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="部门id">
              <el-input v-model="employees.departmentId" disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门名称">
              <el-input v-model="employees.departmentName" disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="个人工号">
              <el-input v-model="employees.workId" disabled="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="职位">
              <el-input v-model="employees.workName" disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="基本工资">
              <el-input v-model="employees.baseSalary" disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="邮箱">
              <el-input v-model="employees.email"  prop="address"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>


      <span slot="footer" class="dialog-footer">
    <el-button @click="insertdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="submitInsertMessage">确 定 添 加</el-button>
  </span>
    </el-dialog>


  </div>
</template>

<script>
    import {reloadEmployee} from "../../viewjs/personal_informationHandler";
    import FileSaver from 'file-saver'
    import XLSX from 'xlsx'
    export default {
        name: "employee_management",
      data()
      {
        return{
          searchInput:"",
          employee: [],
          dialogVisible: false,
          insertdialogVisible:false,
          employees: {
            userId: "",
            userName: "",
            role:"",
            idcard:"",
            email:"",
            gender: "",
            politicaltype: "",
            nationId: "",
            address: "",
            phone: "",
            education: "",
            educationsubject: "",
            school: "",
            departmentId: "",
            departmentName: "",
            workId: "",
            workName: "",
            baseSalary:""
          },
          idcards:"",
          rule:{
             name:[{required:true,message:"输入员工姓名",trigger:"blur"}],
            gender:[{required:true,message:"输入男/女",trigger:"blur"}],
            idCard: [{required: true, message: '请输入身份证号码', trigger: 'blur'}, {
              pattern: /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/,
              message: '身份证号码格式不正确',
              trigger: 'blur'
            }],
            politicaltype:[{required:true,message:"输入政治面貌",trigger:"blur"}],
            nationId: [{required:true,message:"输入民族",trigger:"blur"}],
            address: [{required:true,message:"输入地址",trigger:"blur"}],
            phone: [{required:true,message:"输入11位电话号码",trigger:"blur"}],
            education: [{required:true,message:"输入最高学历",trigger:"blur"}],
            educationsubject: [{required:true,message:"输入专业",trigger:"blur"}],
            school: [{required:true,message:"输入毕业院校",trigger:"blur"}],
            emails:[{required:true,message:"输入格式xx@%%.com",trigger:"blur"}],
          },
          // watch:{
          //   'searchInput'(){
          //         if(this.searchInput ==''|| this.searchInput =='undefined'||this.searchInput == null)
          //         {
          //           this.reloadEmployees()
          //         }
          //   }
          // }
          options: [
            {
              value: 'all',
              label: '查看全部(默认)'
            },
            {
            value: 'admin',
            label: '管理员'
          }, {
            value: 'department',
            label: '部门经理'
          }, {
            value: 'user',
            label: '雇员'
          }],
          rolevalue:"",
          rolecache:"all",
          noEmployeeuser:[],
          usercache:"请选择员工",
          uservalue:"",
          roleinsert:"",
        }
      },
      mounted() {
        this.$store.state.userId = window.sessionStorage.getItem("userId")
        this.reloadnoEmployeeuser()
          this.reloadEmployees()
      },
      methods: {

        //定义导出Excel表格事件
        exportExcel() {
          let xlsxParam = { raw: true }; //转换成excel时，使用原始的格式
          / generate workbook object from table /;
          /* 从表生成工作簿对象 */
          let table =  document.querySelector("#out-table").cloneNode(true)
          // 因为element-ui的表格的fixed属性导致多出一个table，会下载重复内容，这里删除掉
          table.removeChild(table.querySelector(".el-table__fixed-right"));
          table.removeChild(table.querySelector(".el-table__fixed"));
          let wb = XLSX.utils.table_to_book(
            table ,  //elementui 表格的id
            xlsxParam
          );

          /* 获取二进制字符串作为输出 */
          var wbout = XLSX.write(wb, {
            bookType: "xlsx",
            bookSST: true,
            type: "array"
          });
          try {
            FileSaver.saveAs(
              //Blob 对象表示一个不可变、原始数据的类文件对象。
              //Blob 表示的不一定是JavaScript原生格式的数据。
              //File 接口基于Blob，继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
              //返回一个新创建的 Blob 对象，其内容由参数中给定的数组串联组成。
              new Blob([wbout], { type: "application/octet-stream" }),
              //设置导出文件名称
              "员工表.xlsx"
            );
          } catch (e) {
            if (typeof console !== "undefined") console.log(e, wbout);
          }
          return wbout;
        },




          reloadnoEmployeeuser()
          {this.usercache = "请选择员工"
            this.rolecache = ""
            this.noEmployeeuser = []
            this.$axios.post("/getNotInEmployeeUserId").then((res)=>{
              this.noEmployeeuser =res.data
            //  alert(JSON.stringify(this.noEmployeeuser))
            })
          },
        reloadEmployees()
        {

          // alert(this.$store.state.userId)
          this.$axios.post("/getAllEmployee",{
            userId:this.$store.state.userId
          }).then((res)=>{
            //alert(JSON.stringify(res.data))
            this.employee = []
          this.employee =res.data

          //  alert(JSON.stringify(res.data))
          //   for(var i = 0 ; i <JSON.stringify(res.data.length);i++)
          //   {
          //    // alert(JSON.stringify(res.data[i])+"\n")
          //     this.employee[i]=res.data[i]
          //   }
            //alert(JSON.stringify(this.employee[0]))
          //  alert(JSON.stringify(this.employee[1]))
          })
        },
        watchsearch()
        {
          if(this.searchInput ==''|| this.searchInput =='undefined'||this.searchInput == null)
          {
            this.reloadEmployees()
          }
          var role = JSON.stringify(this.rolecache).replace(/\"/g, "")
          var userId = JSON.stringify(this.searchInput).replace(/\"/g, "")
          if(role == 'all')
          {
            this.getEmployeeById()
          }
          else{
            this.getEmployeeByRoleAnduserId(userId,role)
          }


        },
        deleteEmp(data) {
          // alert("this.searchInput")
          // alert(JSON.stringify(data))
          this.$confirm('此操作将清空【' +JSON.stringify(data.userId).replace(/\"/g, "")  + '】的信息, 是否继续,在此之前请先移除该员工的部门信息为闲置?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$axios.post("/deleteEmployeeByuserId",{
                userId:data.userId

            }).then(resp => {
              if (resp.status = 200) {
                this.reloadnoEmployeeuser()
                this.reloadEmployees()
                return this.$message.success("删除成功")
              }
              else {
                return this.$message.error(resp.msg)
              }
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });
        },
        getDetails(row){
          this.$store.commit("setflushemp",row)
          // alert(JSON.stringify(this.$store.state.flushemp))
          // alert(JSON.stringify(row))//此时就能拿到整行的信息
          // alert(JSON.stringify(row.userId).replace(/\"/g, ""))
        },
        handleClose(done) {
          this.$confirm('确认关闭？')
            .then(_ => {
              this.reloadEmployees()
              this.reloadnoEmployeeuser()
              done();
            })
            .catch(_ => {
              this.reloadnoEmployeeuser()
              this.reloadEmployees()
            });
        },
        opendialog(data)
        {
          alert(JSON.stringify(data))
          this.employees = data
          this.dialogVisible=true

        },
        openInsertdialog()
        {
          this.employees.userId = "",
            this.employees.userName= "",
          this.employees.idcard="",
            this.employees.gender= "",
            this.employees.politicaltype= "",
          this.employees.nationId= "",
            this.employees.email = "",
          this.employees.address= "",
          this.employees.phone= "",
          this.employees.education= "",
          this.employees.educationsubject= "",
          this.employees.school="",
          this.employees.departmentId= "",
          this.employees.departmentName= "",
          this.employees.workId="",
          this.employees.workName= "",
          this.employees.baseSalary=""
          this.insertdialogVisible=true

        },
        submitMessage()
        {

          //alert(JSON.stringify(this.employees.idcard))
          this.$axios.post("/updateAcceptDepartmentById",{
            userId:this.employees.userId,
            userName: this.employees.userName,
            gender: this.employees.gender,
            email:this.employees.email,
            idcard: this.employees.idcard,
            politicaltype: this.employees.politicaltype,
            nationId: this.employees.nationId,
            address: this.employees.address,
            phone: this.employees.phone,
            education: this.employees.education,
            educationsubject: this.employees.educationsubject,
            school: this.employees.school,
          }).then((res)=>{

            if(res.status == 200)
            {
              this.$axios.post("/updateusernameAndemailById",{
                userId:this.employees.userId,
                username:this.employees.userName,
                email:this.employees.email
              }).then((resp)=>{

              })
                this.$message.success(JSON.stringify(res.data.msg).replace(/\"/g, ""))
                this.reloadEmployees()
            }
            else{
              this.$message.error(JSON.stringify(res.data.msg).replace(/\"/g, ""))
              this.reloadEmployees()
            }

          })

          this.dialogVisible = false;
        },
        getEmployeeById()
        {
          this.employee = undefined;
         // alert(JSON.stringify(this.searchInput))
          this.$axios.post("/employee/getEmployeeById",{
            userId:this.searchInput
          }).then((res)=>{
          //  alert(JSON.stringify(res.data))
            this.employee = res.data
          })
        },
        getEmployeeByRole(rolevalue)
        {
          var role = JSON.stringify(rolevalue).replace(/\"/g, "")

          // alert(role)
          if(role == 'all')
          {
            this.rolecache = 'all'
            this.reloadEmployees()
            this.searchInput = ""
            return this.$message.success("已加载所有员工信息！")
          }
          if(role == 'admin')
          {
            this.rolecache = 'admin'
          }
          if(role == 'department')
          {
            this.rolecache = 'department'
          }
          if(role == 'user')
          {
            this.rolecache = 'user'
          }
          //alert(JSON.stringify(this.rolecache))
          this.employee = []
          this.$axios.post("/employee/getEmployeeByRole",{
            role:this.rolecache
          }).then((res)=>{
            this.employee = res.data
          })
          this.searchInput = ""
          return this.$message.success(role+"成员已加载成功")
        },
        getEmployeeuserId(userId)
        {

          this.uservalue = userId
          alert(JSON.stringify(this.uservalue))
          this.$axios.post("/getUsernameAndEmailAndroleById",{
            userId:this.uservalue
          }).then((res)=>{
              this.employees.email = res.data.email;
              this.employees.role = res.data.role;
              this.employees.userName = res.data.username;
              this.roleinsert = res.data.role;
          })
          },
        submitInsertMessage()
        {

          //alert(JSON.stringify(this.employees.idcard))
          this.$axios.post("/InsertEmployeeAcceptDepartment",{
            userId:this.uservalue,
            userName: this.employees.userName,
            gender: this.employees.gender,
            email:this.employees.email,
            role: this.roleinsert,
            idcard: this.employees.idcard,
            politicaltype: this.employees.politicaltype,
            nationId: this.employees.nationId,
            address: this.employees.address,
            phone: this.employees.phone,
            education: this.employees.education,
            educationsubject: this.employees.educationsubject,
            school: this.employees.school,
          }).then((res)=>{

            if(res.status == 200)
            {
              this.$axios.post("/updateusernameAndemailById",{
                userId:this.uservalue,
                username:this.employees.userName,
                email:this.employees.email
              }).then((resp)=>{

              })
              this.$message.success(JSON.stringify(res.data.msg).replace(/\"/g, ""))
              this.reloadnoEmployeeuser()
              this.reloadEmployees()
            }
            else{
              this.$message.error(JSON.stringify(res.data.msg).replace(/\"/g, ""))
              this.reloadnoEmployeeuser()
              this.reloadEmployees()
            }

          })

          this.insertdialogVisible = false;
        },

        getEmployeeByRoleAnduserId(userId,role)
        {
          // alert(userId)
          // alert(role)
          this.$axios.post("/employee/getEmployeeByRoleAnduserId",{
            userId:this.searchInput,
            role:role
          }).then((res)=>{

                this.employee = [],
                  this.employee = res.data
                  var datas = JSON.stringify(res.data).replace(/\"/g, "")
                  // alert(datas)
              if(datas != '[]')
               return this.$message.success("获取成功")
              else return this.$message.error("该成员不存在")



          })
        },
        returnlogin(){
          this.$store.commit("setviewPage",1);
          this.$router.push({path: '/home'});
        }
      }
    }
</script>

<style scoped>


</style>
